package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.UserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Title:
 * @BelongProjecet zk2
 * @BelongPackage com.bwie.service.impl
 * @Description:
 * @Copyright 研发一部
 * @Author: Mr.yan
 * @Date: 2024/6/3 9:09
 * @Version V1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public R userLogin(LoginVo loginVo) {
        //1.判断用户名是否存在
        TbUser tbUser = userMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginVo.getUserName())
        );
        if (tbUser == null){
            return R.error(404,"该用户为找到，登录失败");
        }

        //2.判断密码是否正确
        if (!tbUser.getPassword().equals(loginVo.getPassword())){
            return R.error(500,"密码输入错误");
        }

        //3.登录成功,生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").setIssuedAt(new Date())
                .claim("id", tbUser.getId())
                .claim("role", tbUser.getUserRole())
                .compact();

        tbUser.setToken(token);

        return R.success(tbUser);
    }

    @Override
    public R selectUser(Integer id) {

        TbUser tbUser = userMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getId, id)
        );
        return R.success(tbUser);
    }
}
